//
//  ST_DailyFinishedRewardController.swift
//  btvideo
//
//  Created by Jason on 2021/12/10.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
//import Rswift
import SwiftyAttributes
import SwiftyJSON
import QuartzCore

/// 日常任务 完成
class ST_DailyFinishedRewardController: UIViewController {
    
    private var json:JSON
    
    init(taskJson:JSON){
        
        self.json = taskJson
        super.init(nibName: nil, bundle: nil)
        self.overCurrentContext = true
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(before_root_view)
        before_root_view.snp.makeConstraints { make in
            make.width.equalTo(265)
            make.height.equalTo(365+10+34)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        
        before_root_view.addSubview(red_package_imag_view)
        red_package_imag_view.snp.makeConstraints { make in
            make.width.equalTo(265)
            make.height.equalTo(365)
            make.top.centerX.equalToSuperview()
        }
        
        
        before_root_view.addSubview(red_package_label)
        red_package_label.snp.makeConstraints { make in
            make.height.equalTo(20)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(230)
        }
        
        before_root_view.addSubview(red_package_line)
        red_package_line.snp.makeConstraints { make in
            make.height.equalTo(1)
            make.width.equalTo(130)
            make.centerX.equalToSuperview()
            make.top.equalTo(red_package_label.snp.bottom).offset(10)
        }
        
        
        
        before_root_view.addSubview(red_package_value_label)
        red_package_value_label.snp.makeConstraints { make in
            make.height.equalTo(22)
            make.centerX.equalToSuperview()
            make.top.equalTo(red_package_label.snp.bottom).offset(21)
        }
        
        
        before_root_view.addSubview(red_package_close_btn)
        red_package_close_btn.snp.makeConstraints { make in
            make.height.width.equalTo(34)
            make.centerX.equalToSuperview()
            make.top.equalTo(red_package_imag_view.snp.bottom).offset(10)
        }
        
        
        before_root_view.addSubview(receive_award_btn)
        receive_award_btn.snp.makeConstraints { make in
            make.height.width.equalTo(94)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(98)
        }
        
        setup_drew_view()
        
        bind_data()
        
    }
    
    
//    private var clickCloseBtn = false
    
    func rotateTo(json:JSON){
        
//        if !clickCloseBtn{
//
//            self.json = json
//            self.bind_data()
//
//            before_root_view.alpha = 1
//            after_root_view.alpha = 0
//
//            clickCloseBtn = false
//
//            return
//        }
        
//        clickCloseBtn = false
        before_root_view.alpha = 1
        after_root_view.alpha = 0
        
        let animate = CABasicAnimation(keyPath: "transform")
        animate.toValue = CATransform3DMakeRotation(.pi, 0, 1, 0)
        animate.duration = 0.35

        self.before_root_view.layer.add(animate, forKey: nil)
        self.red_package_close_btn.isEnabled = false
        
        main_thread_execute(afterDelay: 0.25) {
            self.json = json
            self.bind_data()
            self.red_package_close_btn.isEnabled = true
        }
        
        
    }
    
    
    private func bind_data(){
        
        
        
        red_package_label.text = json["name"].stringValue + " 任务完成"
        
        let typeValue:String
        
        if let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo,user.sex == .female{
            typeValue = "积分"
            red_package_value_label.text = "获得\(json["price"].stringValue)" + typeValue
        }else{
            typeValue = "金币"
            red_package_value_label.text = "获得\(json["price"].stringValue)" + typeValue
        }
        
        let str0 = "\(typeValue) ".withAttributes([.font(.systemFont(ofSize: 14, weight: .medium)),.textColor(.white)])
        
        str0.append(("+" + json["price"].stringValue).withAttributes([.font(.systemFont(ofSize: 14, weight: .medium)),.textColor(UIColor(hex: 0xFFDE96)!)]))
        
        drew_value_title_label.attributedText = str0
        
    }
    
    
    private func setup_drew_view(){
        
        view.addSubview(after_root_view)
        after_root_view.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(iPhoneXSeries ? -80 : -10)
            make.width.equalTo(375)
            make.height.equalTo(375)
        }
        
        
        
        after_root_view.addSubview(scan_animate_view)
        scan_animate_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(150.0/375.0*ScreenWidth)
            make.center.equalToSuperview()
        }
        
        after_root_view.addSubview(scan_gift_image_view)
        scan_gift_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(116/375.0*ScreenWidth)
            make.center.equalTo(scan_animate_view)
        }
        
        after_root_view.addSubview(drew_title_label)
        drew_title_label.snp.makeConstraints { (make) in
            make.height.equalTo(22)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(scan_animate_view.snp.top).offset(-20)
        }
        
        
        after_root_view.addSubview(drew_value_title_label)
        drew_value_title_label.snp.makeConstraints { (make) in
            make.height.equalTo(22)
            make.centerX.equalToSuperview()
            make.top.equalTo(scan_animate_view.snp.bottom).offset(20)
        }
        
        
    }
    

//     MARK: - properties
    
    fileprivate lazy var before_root_view:UIView = {
        let v = UIView()
        return v
    }()
    
    fileprivate lazy var after_root_view:UIView = {
        let v = UIView()
        v.alpha = 0
        return v
    }()
    
    fileprivate lazy var red_package_imag_view:UIImageView = {
        let v = UIImageView(image: ST_ImageUtils.imageName("receive_daily_task_status_background"))
        return v
    }()
    
    fileprivate lazy var red_package_label:UILabel = {
        let l = UILabel()
        l.textColor = #colorLiteral(red: 1, green: 0.8914952278, blue: 0.6523597836, alpha: 1)
        l.font = .systemFont(ofSize: 14, weight: .regular)
        return l
    }()
    
    fileprivate lazy var red_package_line:UIView = {
        let l = UIView()
        l.backgroundColor = UIColor.init(hex: 0xFFDE96, transparency: 0.4)
        return l
    }()
    
    fileprivate lazy var red_package_value_label:UILabel = {
        let l = UILabel()
        l.textColor = #colorLiteral(red: 1, green: 0.8914952278, blue: 0.6523597836, alpha: 1)
        l.font = .systemFont(ofSize: 16, weight: .semibold)
        return l
    }()
    
    fileprivate lazy var receive_award_btn:UIButton = {
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.addTarget(self, action: #selector(receive_award_handle), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    
    
    fileprivate lazy var red_package_close_btn:UIButton = {
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.setImage(ST_ImageUtils.imageName("receive_daily_task_status_close"), for: .normal)
        btn.addTarget(self, action: #selector(beforeCloseHandle), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    
    fileprivate lazy var scan_gift_image_view:UIImageView = {
       
        let control = UIImageView(image: ST_ImageUtils.imageName("receive_daily_task_coin_icon"))
        return control
    }()
    
    fileprivate lazy var scan_animate_view:LOTAnimationView = {
        
        let path = Bundle.main.path(forResource: "receiveGiftBack", ofType: "json")!
        
        let control = LOTAnimationView.init(filePath: path)
        
        control.contentMode = UIView.ContentMode.scaleAspectFill
        
        control.loopAnimation = true
        
        return control
    }()
    
    
    fileprivate lazy var drew_title_label:UILabel = {
        let l = UILabel()
        l.textColor = .white
        l.font = .systemFont(ofSize: 16, weight: .medium)
        l.text = "获得奖励"
        return l
    }()
    
    fileprivate lazy var drew_value_title_label:UILabel = {
        let l = UILabel()
        return l
    }()
    
}



extension ST_DailyFinishedRewardController{
    
    @objc private func receive_award_handle(){
        
        TIANSession(requestUrl: PH.receiveRewardsApi,parameters: ["award_id":json["id"].stringValue]).withUnretained(self).subscribe{ own , result in
            
            /// 领取任务奖励后 随便发个通知便于 [我的]TAB栏刷新
            NotificationCenter.default.post(name: Notification.Name.nick_name_audit_failure, object: nil)
            
            switch result {
            case .success:
                
                own.before_root_view.alpha = 0
                own.after_root_view.alpha = 1
                own.scan_animate_view.play()
                
                main_thread_execute(afterDelay: 1.5) {
                    own.scan_animate_view.stop()
                    SCComponets.alert_dispatcher?.nextAlert()
                }
                
            case .failure(let err):
                own.toast(text: err.e)
                
                main_thread_execute(afterDelay: 1.5) {
                    own.scan_animate_view.stop()
                    SCComponets.alert_dispatcher?.nextAlert()
                }
            }
            
        }.disposed(by: rx.disposeBag)
        
        
    }
    
    @objc private func beforeCloseHandle(){
        
//        clickCloseBtn = true
        
        before_root_view.alpha = 0
        
        SCComponets.alert_dispatcher?.nextAlert(jump: true)
        
    }
    
}
